package org.jackysoft.file;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;
import org.jackysoft.entity.ReceivedFileItem;
import org.jackysoft.entity.UploadedFileItem;
import org.jackysoft.entity.User;

public class DetachedCriteriaRoom {
	static DetachedCriteriaRoom ins = null;

	private DetachedCriteriaRoom() {

	}

	public static DetachedCriteriaRoom getInstance() {
		if (ins == null) {
			ins = new DetachedCriteriaRoom();
			return ins;
		} else {
			return ins;
		}
	}

	public DetachedCriteria getCountDetachedCriteria(
			final String type,
			final String user, 
			final String folderId,
			final String propertyName) {
		User owner = new User(user);
		DetachedCriteria criteria = null;
		FileType ftype = FileType.getFileType(type);
		switch (ftype) {
		case SENT: {
			criteria = DetachedCriteria.forClass(ReceivedFileItem.class);
			criteria.add(Restrictions.eq("fromer", owner));
		}
			;
			break;
		case UPLOADED: {
			criteria = DetachedCriteria.forClass(UploadedFileItem.class);
			criteria.add(Restrictions.eq("owner", owner));
			criteria.add(Restrictions.eq("folder", folderId));
		}
			;
			break;
		case RECEIVED: {
			criteria = DetachedCriteria.forClass(ReceivedFileItem.class);
			criteria.add(Restrictions.eq("owner", owner));
			criteria.add(Restrictions.eq("enabled", true));
		}
		}
		criteria.setProjection(Property.forName(propertyName).count());
		return criteria;
	}

	public DetachedCriteria createDetachedCriteria(final String type,
			final String user, final String folderid) {
		DetachedCriteria icra = null;
		FileType ftype = FileType.getFileType(type);
		switch (ftype) {
		case RECEIVED:
			icra = getReceiveDetachedCriteria(user);
			break;
		case UPLOADED:
			icra = getUploadDetachedCriteria(user, folderid);
			break;
		case SENT:
			icra = getSentDetachedCriteria(user);
			break;
		default:
			;

		}
		icra.addOrder(Property.forName("createTime").desc());
		return icra;
	}

	public DetachedCriteria getReceiveDetachedCriteria(final String user) {
		User owner = new User(user);
		DetachedCriteria criteria = DetachedCriteria
				.forClass(ReceivedFileItem.class);
		criteria.add(Restrictions.eq("owner", owner));
		criteria.add(Restrictions.eq("enabled", true));
		return criteria;
	}

	public DetachedCriteria getSentDetachedCriteria(final String user) {
		User fromer = new User(user);
		DetachedCriteria criteria = DetachedCriteria
				.forClass(ReceivedFileItem.class);
		criteria.add(Restrictions.eq("fromer", fromer));
		return criteria;
	}

	public DetachedCriteria getUploadDetachedCriteria(final String user,
			final String folderid) {
		User owner = new User(user);
		DetachedCriteria criteria = DetachedCriteria
				.forClass(UploadedFileItem.class);
		criteria.add(Restrictions.eq("folder", folderid));
		criteria.add(Restrictions.eq("owner", owner));
		return criteria;
	}
	
}
